%{
                                                        applyRegion.m V1
                                                     Written by Rajeev Kant
                                                        Sept. 4th, 2020
                                    Coulombe Lab for Cardiovascular Regenerative Engineering
                            Center for Biomedical Engineering, Brown Univeristy, Providence, RI, 02903

This function will apply region masks created in ARA_Analyze to specified
stains and upscale the image if needed so that all downstream analysis
occurs at the same resolution.

By default it is assumed that blue = DAPI/Hoechst and green = vimentin, and
searching for these fluorescence files based on the naming syntax
nameofmergeimage_DAPI. To edit, see lines 40-47

The user may need to edit the following lines: 70-73 (upscaling)

Inputs:
1. filename: RGB input image from ARA_Analyze
2. path: File path of input image
3. polyIF, polyRM: ROI mask specified in ARA_Analyze
4. boundIF, boundRM: Bounding boxes of polyIF and polyRM, taken from
regionprops
5. color: variable to determine what image channel is being cropped
6. scaleFlag: flag variable to determine if upscaling is needed
7. scale: Input scale from ARA_Analyze

Outputs:
1. IF: IF bounded image of color-specified stain
2. RM: RM bounded image of color-specified stain
3. scale: output scale if upscaling occurred


Original publication for citation: 
Kant, R. J., Bare, C. F., and Coulombe, K. L. K. "Tissues with 
patterned vessels or protein release induce vascular chemotaxis
in an in vitro platform", Tissue Eng. Part A, 2021.
doi:10.1089/ten.TEA.2020.0269

%}
function [IF, RM, scale] = applyRegion (filename, path, polyIF, boundIF, polyRM, boundRM, color, scaleFlag, scale)
%% Load in individual stains and repeat IF/R cropping for G and B channels

% Mainly required when non RGB colors are used (e.g. cyan = DAPI), otherwise can directly isolate RGB
% Change filepaths if naming convention is different
if color == 1
    im=imread(strcat(path, filename,'_SMA.tif')); 
    RGBim = imread(strcat(path,file));
elseif color == 2
    im=imread(strcat(path, filename,'_Vim.tif'));
else
    im=imread(strcat(path, filename,'_DAPI.tif'));
end

IF = im;
IF(polyIF == 0) = 0; % Segment initial RGB based on determined mask
IF = imcrop(IF,boundIF.BoundingBox); % Crop ROI
% figure; imshow(IF);

RM = im;
RM(polyRM == 0) = 0; % Segment initial RGB based on determined mask
RM = imcrop(RM,boundRM.BoundingBox); % Crop ROI
%figure; imshow(R);

% Set to grayscale and enhance contrast
IF = adapthisteq(IF(:,:,color));
RM = adapthisteq(RM(:,:,color));

%% Upscale regions if merged input was scaled up so that analysis is performed at same resolution
if scaleFlag == 1
    IF = imresize(IF, 2);
    RM = imresize(RM, 2);
    scale = scale * 2;
end

end % End of applyRegion.m